package com.learner.common.util;

import com.learner.common.http.CommonCode;
import lombok.Data;

/**
* @author ice2020x
* @Date: 2023/2/23
* @Description:  统一异常处理
**/
@Data
public class Result<T> {

    private Boolean success;

    /**
     * 业务自定义状态码
     */
    private int code;
    /**
     * 请求状态描述，调试用
     */
    private String msg;
    /**
     * 请求数据，对象或数组均可
     */
    private T data;

    private Result() {
    }

    /**
     * 成功时候的调用
     *
     * @param data data
     * @param <T>  t
     * @return Result
     */
    public static <T> Result<T> success(T data) {
        Result<T> r = new Result<>();
        r.setSuccess(true);
        r.setCode(200);
        r.setMsg("success");
        r.setData(data);
        return r;
    }


    /**
     * 失败时候的调用
     *
     * @param codeMsg codeMsg
     * @param <T>     t  CommonCode
     * @return Result
     */
    public static <T> Result<T> error(CodeMsg codeMsg) {
        Result<T> r = new Result<>();
        r.setSuccess(false);
        r.setCode(codeMsg.getCode());
        r.setMsg(codeMsg.getMsg());
        return r;
    }

    public static <T> Result<T> error(CommonCode commonCode) {
        Result<T> r = new Result<>();
        r.setSuccess(false);
        r.setCode(commonCode.code());
        r.setMsg(commonCode.message());
        return r;
    }

    /**
     * @Description: 自定义异常时使用
     * @author: fgcy
     * @Params:
     * @since JDK 1.8
     */

    public static <T> Result<T> throwError() {
        Result<T> r = new Result<>();
        return r;
    }


    /*链式编程*/
    public Result code(int code) {
        this.setCode(code);
        return this;
    }

    public Result msg(String msg) {
        this.setMsg(msg);
        return this;
    }

    public Result data(T data) {
        this.setData(data);
        return this;
    }

}
